import React, { useState, useRef, useEffect } from "react";

const OuterClickExample = (props: any) => {
  const [open, setOpen] = useState(false)
  const toggleContainer: any = useRef()

  useEffect(() => {
    window.addEventListener("click", onClickOutsideHandler);
    return () => {
      window.removeEventListener("click", onClickOutsideHandler);
    }
  })
  const onClickHandler = () => {
    setOpen(!open)
  }
  const onClickOutsideHandler = (event: any) => {
    if (open && !(toggleContainer as any).current.contains(event.target)) {
      setOpen(false)
    }
  }
  return (
    <div ref={toggleContainer}>
      <button onClick={onClickHandler}>Select an option</button>
      {open && (
        <ul>
          <li>Option one</li>
          <li>Option two</li>
          <li>Option three</li>
        </ul>
      )}
    </div>
  );
}

export default OuterClickExample;
